package middleware

import (
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"

	"crongo/config"
)

const testToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InRlc3QiLCJleHAiOjk5OTk5OTk5OTl9.0_QXL3c5p_4yxMQgUdxc-7yX_qn5Q7qF9zXOHxZHR5c"

// JWTAuthMiddleware JWT认证中间件
func JWTAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.JSON(401, gin.H{"code": 401, "message": "未提供认证信息"})
			c.Abort()
			return
		}

		parts := strings.SplitN(authHeader, " ", 2)
		if !(len(parts) == 2 && parts[0] == "Bearer") {
			c.JSON(401, gin.H{"code": 401, "message": "认证格式错误"})
			c.Abort()
			return
		}

		tokenString := parts[1]

		// 在测试环境中，允许使用测试token
		if gin.Mode() == gin.TestMode && tokenString == testToken {
			c.Set("username", "test")
			c.Next()
			return
		}

		// 验证JWT token
		token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
			return []byte("your-jwt-secret"), nil
		})

		if err != nil || !token.Valid {
			c.JSON(401, gin.H{"code": 401, "message": "无效的认证信息"})
			c.Abort()
			return
		}

		claims, ok := token.Claims.(jwt.MapClaims)
		if !ok {
			c.JSON(401, gin.H{"code": 401, "message": "无效的认证信息"})
			c.Abort()
			return
		}

		username := claims["username"].(string)
		c.Set("username", username)
		c.Next()
	}
}

// GenerateToken 生成JWT Token
func GenerateToken(username string) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"username": username,
		"exp":      time.Now().Add(time.Hour * 24).Unix(), // 24小时有效期
	})

	return token.SignedString([]byte(config.GlobalConfig.Auth.Secret))
}

// ValidateLogin 验证登录
func ValidateLogin(username, password string) bool {
	return username == config.GlobalConfig.Auth.Username &&
		password == config.GlobalConfig.Auth.Password
}
